package com.wunu.zn.api.appliance.action;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.Gson;
import com.wunu.zn.api.appliance.model.AddressEntity;
import com.wunu.zn.api.appliance.model.BannerEntity;
import com.wunu.zn.api.appliance.model.Machine;
import com.wunu.zn.api.appliance.model.ProductEntity;
import com.wunu.zn.api.appliance.model.UserEntity;
import com.wx.pay.util.CommonUtil;
import com.wx.pay.util.OauthAccessToken;
import com.wx.pay.util.OauthTokenUtil;

import common.AppConst;
import common.plugin.mybatis.Db;
import common.support.MobileParam;
import common.utils.wechat.WxConfigUtil;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("h5/ppmhtv")
public class HxController {
	private static final String baseUrl = "h5/ppmhtv/";
	private static Logger log = Logger.getLogger(HxController.class);
	/**
	 * 扫码
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/scan")
	@ResponseBody
	public String scan(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String url = WxConfigUtil.getRequestURL(request);
			request.setAttribute("url", url);
			map = WxConfigUtil.getWXConfigMap(request, url);
		} catch (Exception e) {
			map.put("result", false);
			log.error("BookController goCheck :" + "apppid=" + map.get("appid") + ";" + "jsapi_ticket="
					+ map.get("jsapi_ticket") + ";" + "nonceStr=" + map.get("nonceStr") + ";" + "signature="
					+ map.get("signature"));
		}
   		map.put("code", 200);
   		return new Gson().toJson(map); 
	}	
	/**
	 * 进入首页
	 */
	@RequestMapping(value="/index")
	public 	String  toAddDevice (Map<String, Object> data,HttpServletRequest request, 
			HttpServletResponse response, Model model) {
		
		try{
			// 授权后要跳转的链接
			String backUri =   AppConst.APP_URL + "/h5/ppmhtv/goIndex";
			backUri = URLEncoder.encode(backUri, "UTF-8");
			String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + "appid=" +  AppConst.APPID
					+ "&redirect_uri=" + backUri
					+ "&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
			response.sendRedirect(url);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			
		}
		return null;
	}
	
	/**
	 * 进入首页
	 * @throws Exception 
	 */
	@RequestMapping(value="/goIndex")
	public 	String  addDevice (Map<String, Object> data,HttpServletRequest request, 
			HttpServletResponse response) throws Exception {
		String location =  AppConst.APP_URL + "experience"; //跳转首页
		try {
			String code = request.getParameter("code");
			String openId = OauthTokenUtil.getOpenId(code);
			/*String openId = "oz0X10bA-bjFoUJkx3jRkvI5VjYg";*/
			log.error("index openId:"+ openId +"addDevice error!");
			data.put("openId", openId);
			response.sendRedirect(location);
		} catch (Exception e) {
			response.sendRedirect(location+"error");
		}
		return null;
	}
    /**
     * 个人中心
     */
    @RequestMapping("/userAuth")
	public String userAuth(HttpServletRequest request, HttpServletResponse response) {
    	try{
			// 授权后要跳转的链接
			String backUri =  AppConst.APP_URL + "/h5/user/goUserAuth";
			log.info("userAuth:------->"+backUri);
			backUri = URLEncoder.encode(backUri, "UTF-8");
			String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + "appid=" + AppConst.APPID
					+ "&redirect_uri=" + backUri
					+ "&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
			response.sendRedirect(url);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
    
	/**
	 * 前往个人中心
	 */
	@RequestMapping("/goUserAuth")
	public String goUserAuth(HttpServletRequest request, HttpServletResponse response) throws Exception  {
	  String location = "";
  	  String code = "";
	  UserEntity userInfo = null;
	  try {
		HttpSession session = request.getSession();
		Object u = session.getAttribute("user");
    	String openId = "";
    	boolean sessionFlag = false;
    	if(u != null && !"".equals(u.toString())){
    		userInfo = (UserEntity)u;
    		code = session.getAttribute("code") != null ? session.getAttribute("code").toString() : "";
    		openId = session.getAttribute("openId") != null ? session.getAttribute("openId").toString() : "";
    		request.setAttribute("openId", openId);
    	}else{
			code = request.getParameter("code");
			OauthAccessToken token = OauthTokenUtil.getOauthAccessToken(code); //获取access_token
			openId = token.getOpenId();
			if(!sessionFlag){
				userInfo = UserEntity.findByOpenId(openId);
				if(userInfo!=null)
			    	session.setAttribute("user", userInfo);
		    		session.setAttribute("openId", openId);
		    		session.setAttribute("code", code);
		    		session.setMaxInactiveInterval(86400);
		    		request.setAttribute("openId", openId);
		    		request.setAttribute("user", userInfo);
			}else{
				userInfo = this.getUserInfo(token.getToken(), openId);
				userInfo.save();
			}
		 }
    	  response.sendRedirect(location);
		} catch (Exception e) {
		  response.sendRedirect(location + "error");
		}
	  return null;
	}
	
	
	/**
	 * 微信网页授权获取用户基本信息，先获取 code，跳转 url 通过 code 获取 openId
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/machineListAuth")
	public String  machineListAuth(MobileParam param,HttpServletRequest request,
			HttpServletResponse response) {
		try{
			
			// 授权后要跳转的链接
			String backUri =   AppConst.APP_URL + "/h5/humiture/machineList";
			log.info("machineAuth:------->"+backUri);
			// URLEncoder.encode 后可以在backUri 的url里面获取传递的所有参数
			backUri = URLEncoder.encode(backUri, "UTF-8");
			// scope 参数视各自需求而定，这里用scope=snsapi_base
			// 不弹出授权页面直接授权目的只获取统一支付接口的openid
			String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + "appid=" +  AppConst.APPID
					+ "&redirect_uri=" + backUri
					+ "&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
			response.sendRedirect(url);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			
		}
		return null;
	}
	/**
     * 获取用户信息
     * @param accessToken 接口访问凭证
     * @param openId 用户标识
     * @return OAuthInfo
     */
	private UserEntity getUserInfo(String accessToken, String openId) throws Exception {
		UserEntity userinfo = null;
		// 拼接请求地址
		String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
		// 获取用户信息
		JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
		if (null != jsonObject) {
			try {
				userinfo = new UserEntity();
				userinfo.set("openid",jsonObject.getString("openid"));
				userinfo.set("nickName",jsonObject.getString("nickname"));
				userinfo.set("sex",jsonObject.get("sex").toString());
				userinfo.set("province",jsonObject.getString("province"));
				userinfo.set("city",jsonObject.getString("city"));
				userinfo.set("country",jsonObject.getString("country"));
				userinfo.set("photo",jsonObject.getString("headimgurl"));
			} catch (Exception e) {
				if (jsonObject.get("errcode") != null) {
					int errorCode = jsonObject.getInt("errcode");
					String errorMsg = jsonObject.getString("errmsg");
					log.error("获取用户信息失败 errcode: " + errorCode + ", errmsg: "+ errorMsg);
				}
				log.error("com.bklovers.org.api.action.CommonController -- getUserInfo() : " + e.getMessage());
				throw e;
			}
		}
		return userinfo;
	}
	
	/**
	 * 绑定设备
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/bind")
	@ResponseBody
	public 	String  bind (HttpServletRequest request, HttpServletResponse response) {
		Map<String,Object> result = new HashMap<String, Object>();
		String deviceId = request.getParameter("deviceId");
		String openId = request.getParameter("openId");
		Machine mc = Machine.getBindMachine(deviceId);
		if(mc!=null){
			if( mc.getBoolean("islet")){
				result.put("code", 0);
			}else{
			    mc.set("islet", true);
			    mc.set("openId", openId);
			    mc.update();
			    result.put("code", 200);
			}
		}else{
			result.put("code", 300);
		}
		return  new Gson().toJson(result);
	}
	
	/**
	 * 解除绑定
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/rebind")
	@ResponseBody
	public 	String  rebind (HttpServletRequest request, HttpServletResponse response) {
		Map<String,Object> result = new HashMap<String, Object>();
		String machineId = request.getParameter("deviceId");
		String openId = request.getParameter("openId");
		Machine mc = Machine.getReBindMachine(machineId,openId);
		try {
			Db.deleteById(Machine.class, mc.get("id"));
			log.error("rebind:machineId openId--->"+machineId+":"+openId);
		} catch (Exception e) {
			result.put("code", 300);
			return  new Gson().toJson(result);
		}
		result.put("code", 200);
		return  new Gson().toJson(result);
	}
	
	/**
	 * 获取用戶设备列表
	 * @param data
	 * @param request
	 * @param response
	 * @param param
	 * @return
	 */
	@RequestMapping(value="/machineList")
	@ResponseBody
	public 	String  getMachineList (HttpServletRequest request, 
			HttpServletResponse response) {
		String openId = request.getParameter("openId");
		Map<String,Object> result = new HashMap<String, Object>();
		List<Map<String, Object>> machines = Machine.getMachineList(openId);
		if(machines !=null){
			result.put("machineList", machines);
			result.put("code", 200);
		}else{
			result.put("code", 0);
		}
		return  new Gson().toJson(result);
	}
	
	/**
	 * 添加地址
	 * @param request
	 * @param response
	 * @param id
	 * @param openId
	 * @param name
	 * @param phone
	 * @param isDefault
	 * @param city
	 * @param district
	 * @param place
	 * @param province
	 * @param code
	 * @return
	 */
	@RequestMapping(value="/addAddress")
	@ResponseBody
	public 	String  addAddress (HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value="id",required=false)  Integer  id ,
			@RequestParam(value="openId",required=false)  String  openId ,
			@RequestParam(value="name",required=false)String name,
			@RequestParam(value="phone",required=false)String phone,
			@RequestParam(value="isDefault",required=false)String isDefault,	
			@RequestParam(value="city",required=false)String city,
			@RequestParam(value="district",required=false)String district,
			@RequestParam(value="place",required=false)String place,
			@RequestParam(value="province",required=false)String province,
			@RequestParam(value="code",required=false) String code) {
		Map<String,Object> result = new HashMap<String, Object>();
		AddressEntity as = new AddressEntity();
		as.set("openId", openId);
		as.set("name", name);
		as.set("phone", phone);
		as.set("city", city);
		as.set("district", district);
		as.set("place", place);
		as.set("province", province);
		as.set("code", code);
		as.set("isDefault", isDefault);
		try {
			if(id!=null){
				as.set("id", id);
				as.update();
			}else{
				as.save();
			}
		} catch (Exception e) {
			result.put("code", 300);
			return  new Gson().toJson(result);
		}
		result.put("code", 200);
		return  new Gson().toJson(result);
	}
	
	/**
	 * 地址列表
	 * @param request
	 * @param response
	 * @param openId
	 * @return
	 */
	@RequestMapping(value="/addressList")
	@ResponseBody
	public 	String  addAddress (HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value="openId",required=false)  String  openId ) {
		Map<String,Object> result = new HashMap<String, Object>();
		 List<Map<String, Object>> addressList = null;
		try {
			addressList = AddressEntity.getAddressList(openId);
		} catch (Exception e) {
			result.put("code", 300);
			return  new Gson().toJson(result);
		}
		result.put("addressList", addressList);
		result.put("code", 200);
		return  new Gson().toJson(result);
	}
	
	/**
	 * 
	 * banner列表
	 * 
	 */
	@RequestMapping(value="/shopIndex")
	public 	void  banner (HttpServletRequest request, HttpServletResponse response )throws Exception {
		Map<String,Object> result = new HashMap<String, Object>();
		String location = "";
		 List<Map<String, Object>> bannerList = null;
		 List<Map<String, Object>> productList = null;
		try {
			bannerList  = BannerEntity.getBannerList();
			productList = ProductEntity.getProductList();
	
		result.put("bannerList", bannerList);
		result.put("productList", productList);
		request.setAttribute("code",  200);
	  	response.sendRedirect(location);
		} catch (Exception e) {
			request.setAttribute("code",  300);
			response.sendRedirect(location+"error");
		}
	}
	
	/**
	 * 产品详情
	 * @param request
	 * @param response
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/productInfo")
	@ResponseBody
	public 	String  productInfo (HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value="id",required=false)  Integer id ) {
		Map<String,Object> result = new HashMap<String, Object>();
		ProductEntity productInfo = null;
		try {
			productInfo =ProductEntity.getProductInfo(id);
		} catch (Exception e) {
			result.put("code", 300);
			return  new Gson().toJson(result);
		}
		result.put("productInfo", productInfo);
		result.put("code", 200);
		return  new Gson().toJson(result);
	}
}
